package com.codexsoft.test;

import com.codexsoft.test.entities.Country;
import com.codexsoft.test.jpamodel.EMF;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import javax.persistence.EntityManager;

/**
 * Created by IntelliJ IDEA.
 * User: lotos
 * Date: 22.08.11
 * Time: 16:51
 * To change this template use File | Settings | File Templates.
 */
public class CountryEditPanel extends Panel {
    Component panel;
    String thisid;
    String cname;
    String cid;
    TextField countryName = new TextField("countryName", new PropertyModel(this, "cname"));
    TextField countryId = new TextField("countryId", new PropertyModel(this, "cid"));

    public CountryEditPanel(String id) {
        super(id);
        this.setOutputMarkupId(true);
        this.setOutputMarkupPlaceholderTag(true);

        panel = this;
        Form form = new Form("editCountryForm");
        form.add(countryName);
        form.add(countryId);
        form.add(new AjaxButton("countrySubmitEditing") {
            @Override
            protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) {
                String cname = (String) countryName.getModelObject();
                String cid = (String) countryId.getModelObject();
                Country c = new Country(cid, cname);
                countryName.setModelObject("");
                countryId.setModelObject("");
                EntityManager em = EMF.get().createEntityManager();
                try {
                    em.persist(c);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    em.close();
                }
                Component empty = new EmptyPanel(panel.getId());
                empty.setOutputMarkupId(true);
                panel.replaceWith(empty);
                panel = empty;
                ajaxRequestTarget.addComponent(panel);
                setResponsePage(UInfoPage.class);
                //panel.redirectToInterceptPage(new UInfoPage());
            }
        });
        add(form);
    }
}
